<template>
  <div class="box">
    <van-nav-bar left-text="取消" left-arrow @click-left="onClickLeft" />
    <div class="top">
      <h2>请输入验证码</h2>
      <p>验证码已发送至(+86){{ phone }}</p>
      <div class="spans">
        <span class="span">
          <input type="text" maxlength="1" v-model="code2" />
        </span>
        <span class="span">
          <input type="text" maxlength="1" v-model="code3" />
        </span>
        <span class="span">
          <input type="text" maxlength="1" v-model="code4" />
        </span>
        <span class="span">
          <input type="text" maxlength="1" v-model="code5" @input="codeLogin" />
        </span>
      </div>
      <div>
        <p style="font-size: 12px; color: #999; margin-top: 20px">
          该手机号未注册春雨，输入验证码后将自动注册
        </p>
      </div>
      <div>
        <p style="font-size: 12px; color: #999; margin-top: 20px">{{ timer }}s后重新获取验证码</p>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { ElMessage } from 'element-plus'
// 倒计时
const timer = ref(localStorage.getItem('timer'))
// 跳转路由
const router = useRouter()
const onClickLeft = () => history.back()
const phone = localStorage.getItem('username') || ''
console.log(phone)
const code = localStorage.getItem('code') || ''
const code1 = code.split('')
console.log(code1)
// 验证码
const code2 = ref('')
const code3 = ref('')
const code4 = ref('')
const code5 = ref('')
setInterval(() => {
  timer.value--
  if (timer.value == 0) {
    router.push('/login')
  }
  localStorage.setItem('timer', timer.value.toString())
}, 1000)

const codeLogin = async () => {
  const codes = code2.value + code3.value + code4.value + code5.value
  console.log(codes)
  await axios
    .post('/api/code/login', {
      code: codes
    })
    .then((res) => {
      console.log(res)
      const token = res.data.userInfo.token
      localStorage.setItem('token', token)
      localStorage.setItem('userInfo', JSON.stringify(res.data.userInfo))
      ElMessage.success('登录成功,3秒后跳转个人中心')
      setTimeout(() => {
        location.href = '/my'
      }, 3000)
    })
}
</script>

<style scoped>
.span {
  width: 40px;
  height: 50px;
  border-bottom: green 1px solid;
}
.spans {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin: 20px;
  margin-left: 0;
}
.span input {
  border: none;
  outline: none;
  width: 100%;
  height: 100%;
  text-align: center;
}
.box {
  background-color: #fff;
  height: 100vh;
  padding: 0 20px;
}
.top {
  margin-top: 100px;
}
.top h2 {
  font-size: 24px;
  font-weight: 700;
}
</style>
